import 'dart:async';

import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:jyofservice/bean/seat_info_bean_entity.dart';
import 'package:jyofservice/util/AesUtil.dart';

class SeatChargePage extends StatefulWidget {
  @override
  _SeatChargePageState createState() => _SeatChargePageState();
}

class _SeatChargePageState extends State<SeatChargePage> {
  late SharedPreferences sharedPreferences;
  String? key;
  int seatNum = 0;
  double onlin = 0.00;
  double connected = 0.00;
  double consume = 0.00;
  double fiteen = 0.00;
  double thirty = 0.00;
  List<SeatInfoBeanData> list = [];
  bool isloading = false;
  Timer? timer;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init().then((onValue) {
      if (onValue != null) {
        getStaticsSeat();
        getSeatList().then((onValue){
          if(onValue.length!=0) {
            countdown(onValue);
          }
        });

      }
    });
  }

  Future init() async {
    sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");
    return key;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('坐席监管',
              style: TextStyle(
                  color: Colors.white, fontSize: ScreenUtil().setSp(45))),
          centerTitle: true,
        ),
        body: Stack(
          children: <Widget>[
            SingleChildScrollView(
              child: Container(
                color: const Color(0xFFF1F1F1),
                child: Column(
                  children: <Widget>[
                    SizedBox(
                      height: ScreenUtil().setHeight(30),
                    ),
                    Container(
                      color: Colors.white,
                      width: ScreenUtil().screenWidth,
                      padding:
                      const EdgeInsets.only(left: 5, top: 5, bottom: 5),
                      child: Text(
                        '今日通话数据统计',
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: ScreenUtil().setSp(40)),
                      ),
                    ),
                    Container(
                      color: Colors.grey,
                      height: ScreenUtil().setHeight(2),
                      width: ScreenUtil().screenWidth,
                    ),
                    Container(
                      color: Colors.white,
                      height: ScreenUtil().setHeight(200),
                      width: ScreenUtil().screenWidth,
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              '$seatNum',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(70)),
                            ),
                            Text('坐席数量',
                                style: TextStyle(
                                    color: Colors.black45,
                                    fontSize: ScreenUtil().setSp(40)))
                          ],
                        ),
                      ),
                    ),
                    getProgressWidget('坐席在线率', onlin, Colors.blue),
                    getProgressWidget('连通率', connected, Colors.orange),
                    getProgressWidget('呼损率', consume, Colors.pinkAccent),
                    getProgressWidget('15秒连通率', fiteen, Colors.purple),
                    getProgressWidget('30秒连通率', thirty, Colors.green),
                    SizedBox(
                      height: ScreenUtil().setHeight(30),
                    ),
                    ListView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (context, index) {
                        Color? color;
                        Color? textColor;
                        String? phoneName;
                        if (list[index].state == "2") {
                          color = Colors.grey;
                          textColor = Colors.black;
                          phoneName = "离席";
                        } else if (list[index].state == "3") {
                          color = Colors.yellowAccent;
                          textColor = Colors.black;
                          phoneName = "置忙";
                        } else {
                          if (list[index].phoneState == "1") {
                            //空闲
                            color = Colors.lightGreen;
                            textColor = Colors.white;
                            phoneName = "空闲";
                          } else if (list[index].phoneState == "2") {
                            //摘机
                            color = Colors.orange;
                            textColor = Colors.white;
                            phoneName = "摘机";
                          } else if (list[index].phoneState == "3") {
                            //摘机
                            color = Colors.white;
                            textColor = Colors.pink;
                            phoneName = "呼入";
                          }else if (list[index].phoneState == "4") {
                            //振铃
                            color = Colors.red;
                            textColor = Colors.white;
                            phoneName = "振铃";
                          } else if (list[index].phoneState == "5") {
                            //通话
                            color = Colors.blue;
                            textColor = Colors.white;
                            phoneName = "通话";
                          } else if (list[index].phoneState == "6") {
                            //拨号
                            color = Colors.purple;
                            textColor = Colors.white;
                            phoneName = "拨号";
                          }else if (list[index].phoneState == "7") {
                            //通话
                            color = Colors.blue;
                            textColor = Colors.white;
                            phoneName = "通话";
                          }else if (list[index].phoneState == "8") {
                            //拨号
                            color = Colors.brown;
                            textColor = Colors.white;
                            phoneName = "呼出";
                          }else if (list[index].phoneState == "9") {
                            //拨号
                            color = Colors.green;
                            textColor = Colors.white;
                            phoneName = "振铃";
                          }else if (list[index].phoneState == "10") {
                            //通话
                            color = Colors.blue;
                            textColor = Colors.white;
                            phoneName = "通话";
                          }else if (list[index].phoneState == "11") {
                            //拨号
                            color = Colors.greenAccent;
                            textColor = Colors.white;
                            phoneName = "未挂";
                          }
                        }


                        return _getServicePerson(
                            context,
                            index,
                            list[index].state??"",
                            list[index].realName ?? "",
                            list[index].onlinetime,
                            color,
                            phoneName??"",
                            textColor);
                      },
                      itemCount: list.length,
                    )
                  ],
                ),
              ),
            ),

            Offstage(
              offstage: isloading,
              child: SpinKitFadingCircle(
                color: Colors.blue,
                size: 50.0,
              ),
            )
          ],
        ));
  }

  Widget _getServicePerson(
      BuildContext context,
      int index,
      String state,
      String name,
      int? onlineTime,
      Color? color,
      String phontState,
      Color? textcolor) {
    String online = "";

    Image iconImage;
    if (state == "2") {
      //离席
      iconImage = Image.asset(
        'images/kefutouxiang_97.png',
        width: ScreenUtil().setWidth(100),
      );
      online="0小时0分0秒";

    } else {
      iconImage = Image.asset(
        'images/kefutouxiang.png',
        width: ScreenUtil().setWidth(100),
      );
      int  ss = (onlineTime! % 60).toInt();
      int mm = ((onlineTime % 3600) / 60).toInt();
      int hh = (onlineTime / 3600).toInt();
      online = hh.toString() + "小时" + mm.toString() + "分" + ss.toString() + "秒";

    }

    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 10, top: 20, right: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(5),
            child: Text(
              ((index + 1).toString()) ?? "",
              style: TextStyle(
                  color: Colors.black, fontSize: ScreenUtil().setSp(35)),
            ),
          ),
          iconImage,
          Text(
            name??"",
            style: TextStyle(
                color: Colors.black, fontSize: ScreenUtil().setSp(35)),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(),
          ),
          Image.asset(
            'images/shijian.png',
            width: ScreenUtil().setWidth(40),
          ),
          Text(
            online,
            style: TextStyle(
                color: Colors.black, fontSize: ScreenUtil().setSp(35)),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(),
          ),
          Container(
              width: ScreenUtil().setWidth(120),
              height: ScreenUtil().setHeight(70),
//            color: color,
              decoration: BoxDecoration(
                color: color,
                shape: BoxShape.rectangle,
              ),
              child: Center(
                child: Text(
                  phontState,
                  style: TextStyle(
                      color: textcolor, fontSize: ScreenUtil().setSp(35)),
                ),
              )),
        ],
      ),
    );
  }

  Widget getProgressWidget(String title, double num, Color color) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(10),
      height: ScreenUtil().setHeight(90),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              '$title',
              style: TextStyle(
                  color: Colors.black, fontSize: ScreenUtil().setSp(35)),
            ),
          ),
          Expanded(
              flex: 2,
              child: Stack(
                alignment: const Alignment(0.5, 0.5),
                children: <Widget>[
                  SizedBox(
                      height: ScreenUtil().setHeight(60),
                      child: LinearProgressIndicator(
                        value: (num / 100),
                        backgroundColor: Colors.black12,
                        valueColor: AlwaysStoppedAnimation<Color>(color),
                      )),
                  Text(
                    num.toString() + "%",
                    style: TextStyle(
                        color: Colors.black, fontSize: ScreenUtil().setSp(40)),
                  )
                ],
              ))
        ],
      ),
    );
  }

  Future getStaticsSeat() async {
    String aesData= await AesUtil.encodeBase64();
    var data = {"key": key,"ClientType":"phone","ClientKey":aesData};
    Response response = await Dio().post(
        WebConfig().baseUrl +
            "Statistics/GetMyDepartmentPhoneInfo",
        data: data);

    isloading = true;
    if (mounted) {
      setState(() {
        if (response.data["Code"] == "200") {
          seatNum = int.parse(response.data["Data"][0]["a"]);
          String str2 = response.data["Data"][2]["a"];
          String str3 = response.data["Data"][3]["a"];
          String str4 = response.data["Data"][4]["a"];
          String str5 = response.data["Data"][5]["a"];

          connected = double.parse(str2.substring(0, str2.length - 1));
          consume = double.parse(str3.substring(0, str3.length - 1));
          fiteen = double.parse(str4.substring(0, str4.length - 1));
          thirty = double.parse(str5.substring(0, str5.length - 1));
        }
      });
    }
    return response.data;
  }

  Future getSeatList() async {
    String aesData= await AesUtil.encodeBase64();
    var data = {"key": key,"ClientType":"phone","ClientKey":aesData};
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/GetMyDepartmentSeatList",
        data: data);
    String ids = "";
    if (response.data["Code"] == "200") {
      for (int i = 0; i < response.data["Data"].length; i++) {
        if(i!=response.data["Data"].length-1) {
          ids+=response.data["Data"][i]["ID"].toString()+",";
        }else{
          ids+=response.data["Data"][i]["ID"].toString();
        }

      }
    }
    return ids;

  }

  Future getSeatInfoList(String idStr) async {
    list.clear();
    String aesData= await AesUtil.encodeBase64();
    var data = {"key": key,"list":idStr,"ClientType":"phone","ClientKey":aesData};
    Response response = await Dio().post(
        WebConfig().baseUrl + "Phone/GetMyDepartmentSeatInfo",
        data: data);
    if (response.data["Code"] == "200") {
      for (int i = 0; i < response.data["Data"].length; i++) {
        SeatInfoBeanData seatInfoBeanData = SeatInfoBeanData.fromJson(response.data["Data"][i]);
        list.add(seatInfoBeanData);
      }
    }
    print(response.data.toString());

    if(mounted) {
      double a = 0.00;
      for(int i =0;i<list.length;i++) {
        if(list[i].state!="2") {
          a++;
        }
      }
      double st = a/(list.length);


      onlin = st*100;
      if (mounted) {
        setState(() {});
      }
    }


    return response.data;

  }


  //刷新
  Future _onRefresh() async {
    getStaticsSeat();
    getSeatList().then((onValue){
      if(onValue.length!=0) {
        countdown(onValue);
      }
    });
  }
  void countdown(String ids){
    timer =  new Timer.periodic(new Duration(seconds: 1), (timer) {
      getSeatInfoList(ids);
    });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    timer?.cancel();
    timer = null;
    super.dispose();
  }
}
